<template>
    <article class="lm">
        <el-dialog title="" :visible.sync="dialogFormVisible">
            <div class="rm-tit ub ub-ac">
                <div class="f28 c-wh fw500">{{i18n.t('layout.login')}}</div>
                <!-- <p class="ub-f1 f14 tx-r" @click="switchType">{{type === 'phone' ? i18n.t('layout.emailLogin') : i18n.t('layout.phoneLogin')}}</p> -->
            </div>
            <el-form class="login-form p20" autoComplete="on" :model="formData" :rules="rules" ref="loginForm" label-position="left">
                <el-form-item v-show="type === 'phone'" prop="username">
                    <el-input :placeholder="i18n.t('layout.phonePlace')" v-model="formData.username" autoComplete="on" class=" mt3" clearable>
                        <el-select v-model="formData.areaCode" slot="prepend">
                            <el-option v-for="item in countrys" :key="item.value" :label="item.label" :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">+{{ item.value }}</span>
                            </el-option>
                        </el-select>
                    </el-input>
                </el-form-item>
                <el-form-item v-show="type === 'email'" prop="email">
                    <el-input :placeholder="i18n.t('layout.emailPlace')" v-model="formData.email" clearable class="bor75"></el-input>
                </el-form-item>

                <el-form-item v-show="loginType === 'pwd'" prop="password">
                    <el-input type="password" :placeholder="i18n.t('layout.pwd')" prefix-icon="ot-icon-lock" v-model="formData.password" class="bor75" clearable @keyup.enter.native="handleLogin"></el-input>
                </el-form-item>
                <el-form-item v-show="loginType === 'code'" prop="code">
                    <div class=" ub reg-inline">
                        <el-input :placeholder="i18n.t('layout.codeEnter')" v-model="formData.code" clearable class="ub-f1 bor75" style="width: auto;"></el-input>
                        <el-button id="lcbox" plain class="ml20 bor75" :disabled="countDisabled">{{countDownText}}</el-button>
                    </div>
                </el-form-item>


                <!-- <div class="tx-r pb30"><a href="javascript:void(0)" class="c-blu cur" @click="switchLoginType">{{loginType === 'pwd' ? '手机验证码登录' : '密码登录'}}</a></div> -->

                <el-button class="mt20 bor75" type="primary" style="width: 100%" :loading="loading" @click.native.prevent="handleLogin">{{i18n.t('layout.login')}}</el-button>
                <div class="mt60">
                    <a href="javascript:void(0)" class="c-blu" @click="jumpReset">{{i18n.t('layout.forgetPwd')}}</a>
                </div>
                <div class="mt20">
                    <a href="javascript:void(0)" class="c-blu" @click="jumpReg"><span class="c-wh">还没注册？</span>{{i18n.t('layout.regUser')}}</a>
                </div>
            </el-form>
        </el-dialog>

    </article>
</template>

<script>
import i18n from 'src/i18n'

import 'assets/js/riddler-sdk-0.2.1'

import RegModal from 'components/user/RegModal' 
import ResetPasswordModal from 'components/user/resetPasswordModal' 

import { APIlogin, APIsecured, APIgetPhoneCode, APIgetEmailCode } from 'api'

import { validatePhone, validatEmail } from 'utils/validate'
import { setToken, setPerson } from 'utils/auth' // 验权

export default {
    data(){
        const validateUsername = (rule, value, callback) => {
            if (this.type === 'phone' && !validatePhone(value)) {
                callback(new Error(i18n.t('layout.phoneValite')))
            } else {
                callback()
            }
        }
        const validateEmail = (rule, value, callback) => {
            if (this.type === 'email' && !validatEmail(value)) {
                callback(new Error(i18n.t('layout.emailValite')))
            } else {
                callback()
            }
        }
        const validatePass = (rule, value, callback) => {
            if (this.loginType === 'pwd' && value.length < 5) {
                callback(new Error(i18n.t('layout.pwdValite')))
            } else {
                callback()
            }
        }
        const validateCode = (rule, value, callback) => {
            if (this.loginType === 'code' && value === '') {
                callback(new Error(i18n.t('layout.codeEnter')))
            } else {
                callback()
            }
        }

        return {
            i18n,
            dialogFormVisible: false,
            yunFlag: false,
            type: 'phone',
            loginType: 'pwd', //'pwd' or 'code'

            countDisabled: false,
            countDownText: i18n.t('layout.getCode'),

            formData: {
                areaCode: '86',
                username: '',
                password: '',
                email: '',
                code: ''
            },
            rules: {
                username: [{ required: true, trigger: ['blur', 'change'], validator: validateUsername }],
                email: [{ required: true, trigger: ['blur', 'change'], validator: validateEmail }],
                password: [{ required: true, trigger: ['blur', 'change'], validator: validatePass }],
                code: [{ required: true, trigger: ['blur', 'change'], validator: validateCode }],
            },
            loading: false,

            countrys: [
                { value: '86', label: '中国'},
                // { value: '84', label: 'Việt nam'}
            ]
        }
    },
    components: {

    },
    computed: {

    },
    beforeDestroy: function(){

    },
    mounted(){

    },
    methods:{
        init(){ 
            // 云片图片验证初始化
            this.yunpianInit();
        },

        showModal(){
            this.dialogFormVisible = true;

            if (this.yunFlag === true){
                return;
            }
            this.$nextTick(() => {
                this.init();
                this.yunFlag = true;
            })
        },

        hideModal(){
            this.dialogFormVisible = false;
        },

        switchType(){
            this.type = this.type === 'phone' ? 'email' : 'phone';
        },

        switchLoginType(){
            this.loginType = this.loginType === 'pwd' ? 'code' : 'pwd';
        },

        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;

                    let ops = {
                        host: '6bbicon'
                    }

                    if (this.type === 'phone'){
                        ops.username = this.formData.username;
                        ops.areaCode = this.formData.areaCode;
                    } else {
                        ops.username = this.formData.email;
                    }

                    if (this.loginType === 'pwd'){
                        ops.password = this.formData.password;
                    } else {
                        ops.code = this.formData.code;
                    }
                    APIlogin(ops).then(res => {

                        setToken(res.data); //设置登录状态
                        setPerson(JSON.stringify({username: ops.username, areaCode: ops.areaCode}));

                        this.loading = false;
                        this.hideModal();
                        this.$message({
                            type: 'success',
                            message: i18n.t('layout.loginSuccess')
                        });

                        location.reload();
                    }, err => {
                        this.loading = false;
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        jumpReg(){
            this.hideModal();
            this.$nextTick(() => {
                RegModal.show();
            })
        },

        jumpReset(){
            this.hideModal();
            this.$nextTick(() => {
                ResetPasswordModal.show();
            })
        },

        yunpianInit(){
            let _self = this;
            // 初始化
            new YpRiddler({
                expired: 10,
                mode: 'dialog',
                container: document.getElementById('lcbox'),
                noButton: true,
                appId: '136cc634c6d743a5a0e4dba0c27165a1',
                version: 'v1',
                onError: function (param) {
                    if(param.code == 429) {
                        // alert('请求过于频繁，请稍后再试！')
                        _self.$message({
                            type: 'error',
                            message: i18n.t('layout.yrPrompt')
                        });
                        return
                    }
                    // 异常回调
                    // console.error('验证服务异常')
                    _self.$message({
                        type: 'error',
                        message: i18n.t('layout.yrError')
                    });
                },
                onSuccess: function (validInfo, close) {
                    // 成功回调
                    // alert(`验证通过！token=${validInfo.token}, authenticate=${validInfo.authenticate}`)
                    _self.$message({
                        type: 'success',
                        message: i18n.t('layout.yrSuccess')
                    });
                    _self.getCode(validInfo.token, validInfo.authenticate);
                    close()
                },
                onFail: function (code, msg, retry) {
                    // 失败回调
                    _self.$message({
                        type: 'error',
                        message: i18n.t('layout.yrFail')
                    });
                    retry()
                },
                beforeStart: function (next) {
                    if (!validatePhone(_self.formData.username)){
                        _self.$message({
                            type: 'error',
                            message: i18n.t('layout.phoneValite')
                        });
                        return;
                    }
                    // console.log('验证马上开始')
                    next()
                },
                onExit: function() {
                    // 退出验证 （仅限dialog模式有效）
                    // console.log('退出验证')
                }
            })
        },

        getCode(token, authenticate){

            let ops = {
                token, 
                authenticate
            }
            
            let API;

            if (this.type === 'phone'){
                API = APIgetPhoneCode;
                ops.mobile = this.formData.username;
                ops.areaCode = this.formData.areaCode;
            } else {
                API = APIgetEmailCode;
                ops.email = this.formData.email;
            }

            API(ops).then(res => {
                
                // 开始倒计时
                this.startCountDown();
            })
        },

        startCountDown(){

            let num = 60;
            this.countDownText = num + 's';
            this.countDisabled = true;
            let fn = () => {
                setTimeout(() => {

                    if (num > 0){
                        --num;
                        this.countDownText = num + 's';
                        fn();
                    } else {
                        this.countDisabled = false;
                        this.countDownText = i18n.t('layout.getCode');           
                    }

                }, 1000)
            }

            fn();

        },
    }
}
</script>

<style>
.bor75{border-radius: 75px;}
.lm .el-dialog{ width: 540px; }
.lm .el-select .el-input__inner {width: 80px;}
.lm .el-select-dropdown{width: 200px;}
.lm .el-form-item__content>.el-input-group, .lm .el-form-item__content .bor75>.el-input__inner{border-radius: 75px; overflow: hidden;}
</style>
<style lang="scss" scoped>
.rm-tit{
    border-bottom: 1px solid #192038; margin-bottom: 26px;
    &>div{
        padding: 0 17px 20px 17px; border-bottom: 2.5px solid #3366FF;
    }
    &>p{
        color: #1890FF;
    }
}
.reg-inline>*{display: block;}
</style>


